#include <stdio.h>
#include <windows.h>
#include "snake/global.h"
 
// win api 
static void GotoXY(unsigned int x,unsigned int y)
{
    COORD coord;
    coord.X = x; // c > x
    coord.Y = y; // r > y
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

// win api
static void SetColor(int c)
{
    //SetConsoleTextAttribute
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), c); 
}



static void DrawBlock(int r,int c) 
{
    
    SetColor(FOREGROUND_INTENSITY|FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE);
    GotoXY(CTC(c),CTR(r)); 
    printf("%c%c",'[',']'); 
}

/**
 * @description: 绘制游戏地图围墙
 * @param {int} ofs_r 行偏移
 * @param {int} ofs_c 列偏移
 * @param {int} height 高
 * @param {int} width 宽
 * @return {*}
 */
static void DrawMap(int ofs_r,int ofs_c,int height,int width)
{
    // 画行 从上往下
    for(int r = ofs_r;r < ofs_r + height + 1;r++)
    {
        DrawBlock(r,ofs_c - 1);
        DrawBlock(r,ofs_c + width);
    }
    // 画行 从左往右
    for(int c = ofs_c - 1;c < ofs_c + width + 1;c++)
    {
        DrawBlock(ofs_r - 1,c);
        DrawBlock(ofs_r + height ,c);
    }
}

static void DrawString()
{

    SetColor(FOREGROUND_INTENSITY|FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE);
    GotoXY(GTRC(MAP_WIDTH + 4),GTRR(1));
    printf("score");

}

// 画蛇
static void DrawSnake()
{
    GotoXY(GTRC(mysnake.body_node[0].c),GTRR(mysnake.body_node[0].r));
    printf("#");
    for(unsigned int i = 1;i < mysnake.body_length;i++)
    {
        GotoXY(GTRC(mysnake.body_node[i].c),GTRR(mysnake.body_node[i].r));
        printf("*");
    }
    
}

// 画食物
static void DrawFood()
{
    if(food.is_draw == 0)
    {
        GotoXY(GTRC(food.c),GTRR(food.r));
        printf("+");
        
    }
}

// 画分数
static void DrawScore()
{
    GotoXY(GTRC(MAP_WIDTH + 4),GTRR(3));
    printf("%d",mysnake.body_length-3);

}

void DrawClearNode(int r,int c)
{
    GotoXY(GTRC(c),GTRR(r));
    printf(" ");
}

/**
 * @description:
 * @return {*}
 */
void DrawClear(void)
{
    system("cls");  
}


void DrawGameStart(void)
{
    DrawClear();  
    SetColor(FOREGROUND_INTENSITY|FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE);
    GotoXY(CTC(10),CTR(10));
    printf("Game:Snake");

}

void DrawGameMapInit(void)
{
    DrawClear();  
    DrawMap(MAP_OFFSET_ROW,MAP_OFFSET_COL,MAP_HEIGHT,MAP_WIDTH);
    DrawString();
    
}

/**
 * @description: 刷新地图画面
 * @return {*}
 */
void DrawRefreshGameMap(void)
{
    
    DrawSnake(); // 画蛇
    DrawFood(); // 画食物
    DrawScore(); // 画分数
}


void DrawGameEnd(void)
{
    DrawClear();
    SetColor(FOREGROUND_INTENSITY|FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE);
    GotoXY(CTC(10),CTR(10));
    printf("game over");

}
